﻿local rL=rLua
if not rL then return end
local types=rL.ObjTypes
if type(types)~="table" then return end

local GUI=rL.GUI

function rL.SimpCode(str)
	return str:gsub("\n%s+","\n"):gsub("^%s+","")
end

function rL.RGB2ColorCode(r,g,b)
    return format("%02x%02x%02x",(r or 1)*255,(g or 1)*255,(b or 1)*255)
end

function rL.Str2Hex(str)
	local ret={}
	for i=1,str:len() do
		tinsert(ret,format("%02x",str:sub(i,i):byte()))
	end
	return concat(ret," ")
end

function types.Ver(reply,obj)
	local funcs={}
	for name,code in pairs(rL.db.code) do
		tinsert(funcs,{n=name,l=code:len(),a=rL.db.autorun[name]})
	end
	obj.Type="VerReply"
	obj.Ver=rL.Version
	obj.FuncList=funcs
	reply(obj)
end

function types.VerReply(reply,obj,sender)
	obj.Bytes=0
	obj.funcList={}
	for index,funcInfo in ipairs(obj.FuncList) do
		obj.Bytes=obj.Bytes+funcInfo.l
		tinsert(obj.funcList,funcInfo.n)
	end
	if obj.timeStamp then obj.Latency=GetTime()-obj.timeStamp end
	if GUI then
		GUI.ServerCache[sender]=obj
		GUI.Update()
	end
end

function types.RunCode(reply,obj,sender,SessionID)
	local result={rL.dostring(obj.Code,sender,SessionID,obj)}
	reply{Type="RunCodeResult",Result=result,FuncName=obj.FuncName}
end

rL.RunCodeResult=setmetatable({},{__mode="v"})
function types.RunCodeResult(reply,obj,sender)
	if obj.Result[1] then
		local r={}
		for i=2,#obj.Result do
			tinsert(r,tostring(obj.Result[i]))
		end
		rL.log(("%s-%s运行完毕:%s"):format(sender,obj.FuncName or "",#r>0 and table.concat(r," ") or "无返回值"))
	else
		rL.log(sender.."-错误:"..obj.Result[2])
	end
	tinsert(rL.RunCodeResult,obj.Result)
end

function types.OperationResult(reply,obj,sender)
	rL.log(("%s:%s"):format(sender,obj.Text))
	if obj.Text:find("成功注入") or obj.Text:find("成功删除") then
		reply{Type="Ver"}
	end
end

function types.SetFunc(reply,obj,sender)
	if obj.Code:len()>0 then
		rL.db.code[obj.Name]=obj.Code
		rL.db.autorun[obj.Name]=obj.Autorun
		reply{Type="OperationResult",Text=("成功注入函数%s共%d字节"):format(obj.Name,obj.Code:len())}
	else
		rL.db.code[obj.Name]=nil
		rL.db.autorun[obj.Name]=nil
		reply{Type="OperationResult",Text=("成功删除函数%s"):format(obj.Name)}
	end
end

function types.GetFunc(reply,obj,sender)
	if rL.db.code[obj.Name] then
		reply{Type="GetFuncResult",Name=obj.Name,Code=rL.SimpCode(rL.db.code[obj.Name]),Autorun=rL.db.autorun[obj.Autorun]}
	else
		reply{Type="OperationResult",Text=("未找到函数%s"):format(obj.Name)}
	end
end

function types.GetFuncResult(reply,obj,sender)
	if GUI then
		GUI.code.Text=obj.Code
		GUI.sendTarget.Text=sender
		GUI.cboFunc.Text=obj.Name
	end
end

function types.RunFunc(reply,obj,sender)
	if rL.db.code[obj.Name] then
		types.RunCode(reply,{Code=rL.db.code[obj.Name],FuncName=obj.Name},sender)
	else
		reply{Type="OperationResult",Text=("未找到函数%s"):format(obj.Name)}
	end
end
